/*
 * Copyright (c) 2020 - present, Inspur Genersoft Co., Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */

package com.inspur.edp.lcm.metadata.core;

import com.inspur.edp.lcm.metadata.api.entity.GspMetadata;
import com.inspur.edp.lcm.metadata.api.entity.uri.MetadataURI;
import com.inspur.edp.lcm.metadata.api.exception.MetadataExceptionCode;
import com.inspur.edp.lcm.metadata.api.exception.MetadataNotFoundException;
import com.inspur.edp.lcm.metadata.api.service.RefCommonService;
import com.inspur.edp.lcm.metadata.common.Utils;
import com.inspur.edp.lcm.metadata.devcommon.ManagerUtils;
import org.springframework.util.StringUtils;

/**
 * @author zhaoleitr
 */
public class RefCommonServiceImp implements RefCommonService {

    @Override
    public GspMetadata getRefMetadata(String metadataID) {
        return getRefMetadata(new MetadataURI(metadataID), null, null);
    }

    @Override
    public GspMetadata getRefMetadata(MetadataURI targetURI, MetadataURI sourceURI, String projectPath) {
        projectPath = StringUtils.isEmpty(projectPath) ? Utils.getMetadataPath() : projectPath;
        if (StringUtils.isEmpty(projectPath)) {
            throw new MetadataNotFoundException("Lcm", MetadataExceptionCode.PROJECT_PATH_IS_INVALID, "元数据归属工程路径为空，无法找到元数据：" + targetURI.getURIDesc(), null);
        }
        String absolutePath = ManagerUtils.getAbsolutePath(projectPath);
        GspMetadata gspMetadata = new RefCommonCoreService().getRefMetadata(targetURI, sourceURI, absolutePath);

        String devRootPath = Utils.handlePath(ManagerUtils.getDevRootPath());
        if (gspMetadata.getRelativePath() != null && gspMetadata.getRelativePath().startsWith(devRootPath)) {
            gspMetadata.setRelativePath(gspMetadata.getRelativePath().substring(devRootPath.length()).substring(1));
        }
        return gspMetadata;
    }
}
